package com.zja.servlet;

import com.zja.model.Article;
import com.zja.model.JsonResponse;
import com.zja.model.User;
import com.zja.service.ArticleService;
import com.zja.service.Impl.ArticleServiceImpl;
import com.zja.service.Impl.KnowledgeBaseServiceImpl;
import com.zja.service.KnowledgeBaseService;
import com.zja.util.ServletUtil;

import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Timestamp;
/**
 * @author JA
 * @date: 2025/5/4
 * description:创建文章
 */

@WebServlet("/api/article/create")
public class CreateArticleServlet extends HttpServlet {
    private final ArticleService articleService = new ArticleServiceImpl();
    private final KnowledgeBaseService knowledgeBaseService = new KnowledgeBaseServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");

        User user = (User) req.getSession().getAttribute("currentUser");
        if (user == null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("请先登录"));
            return;
        }

        String title = req.getParameter("title");
        String content = req.getParameter("content");
        Long knowledgeBaseId = Long.valueOf(req.getParameter("knowledgeBaseId"));

        // 权限校验
        if (!knowledgeBaseService.userHasManagePermission(user.getId(), knowledgeBaseId)) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("无权在该知识库中发表文章"));
            return;
        }

        Article article = new Article(null, title, content, user.getId(), knowledgeBaseId,
                new Timestamp(System.currentTimeMillis()), new Timestamp(System.currentTimeMillis()));

        boolean success = articleService.createArticle(article);
        if (success) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.success("创建成功"));
        } else {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("创建失败"));
        }
    }
}
